package com.xxkj.drugtraceability.ui.doctoradvicecollection

import android.app.DatePickerDialog
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.xxhis.refactor.eventbus.MessageCode
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMActivity
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.databinding.*
import com.xxkj.drugtraceability.dialog.BlueDialog
import com.xxkj.drugtraceability.dialog.YellowDialog
import com.xxkj.drugtraceability.ext.clickN
import com.xxkj.drugtraceability.lifecycle.KtxManager
import com.xxkj.drugtraceability.scan.BarcodeType
import com.xxkj.drugtraceability.utils.CommonUtils
import com.xxkj.drugtraceability.utils.showCompleteToast
import com.xxkj.drugtraceability.utils.toast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.*

/**
 * author: zhoujingjin
 * created on: 2024/9/10 14:43
 * description:医嘱发药采集
 */
class DoctorAdviceCollectionActivity:BaseVMActivity() {
    private val binding by binding<ActivityDoctorAdviceBinding>(R.layout.activity_doctor_advice)
    private val viewModel by viewModel<DoctorAdviceCollectionViewModel>()
    private lateinit var adapter: DoctorAdviceCollectionAdapter
    private var patientId:String?=""
    override fun initView() {
        binding.apply {
            toolBar.title = ""
            setSupportActionBar(toolBar)
            toolBar.setNavigationOnClickListener {
                onBackPressed()
            }
            recyclerView.layoutManager = LinearLayoutManager(this@DoctorAdviceCollectionActivity)
            adapter = DoctorAdviceCollectionAdapter{
                viewModel.barcode = ""
                viewModel.lastIndex = viewModel.selectIndex.value?:-1
                viewModel.selectIndex.postValue(it)
            }
            llDate.clickN {
                showDatePicker()
            }
            tvCancel.clickN {
                YellowDialog(this@DoctorAdviceCollectionActivity,resources.getString(R.string.cancel_all)){
                    //清空所有追溯码
                    finish()
                }
            }
            tvClear.clickN {
                YellowDialog(this@DoctorAdviceCollectionActivity,resources.getString(R.string.clear_all)){
                    //清空所有追溯码
                    adapter.data.forEach {
                        it.drugTracInfoList?.clear()
                        it.isSelected = false
                    }
                    viewModel.selectIndex.value = -1
                    adapter.notifyDataSetChanged()
                }
            }
            tvSave.clickN {
                var alert = false
                var noData = true
                adapter.data.forEach {
                    if (!it.drugTracInfoList.isNullOrEmpty()){
                        noData = false
                    }
                    var size = 0
                    it.drugTracInfoList?.forEach { drugInfo ->
                        if (drugInfo.drugTracCodeNum != null) {
                            size += drugInfo.drugTracCodeNum!!.toInt()
                        } else {
                            size++
                        }
                    }
                    var needCount = 0
                    needCount = try {
                        it.drugNum?.toDoubleOrNull()?.toInt() ?: 0
                    } catch (e: Exception) {
                        0
                    }
                    if (size < needCount) {
                        alert = true
                    }
                }
                if (noData){
                    //提示没有任何数据
                    YellowDialog(this@DoctorAdviceCollectionActivity,resources.getString(R.string.no_data),type = 1){

                    }
                }else{
                    if (alert){
                        BlueDialog(this@DoctorAdviceCollectionActivity,resources.getString(R.string.scan_not_all)){
                            //保存数据
                          val filter =  viewModel.prescriptioninfo.value?.filter {
                               val filter = it.drugInfoList.filter { drugInfoBean ->
                                    !drugInfoBean.drugTracInfoList.isNullOrEmpty()
                                }
                                filter.isNotEmpty()
                            }
                            viewModel.finishScanDrugCode(FinishAdviceRequest("2",filter,viewModel.Prescriptionbarcode))
                        }
                    }else{
                        //保存数据
                        viewModel.finishScanDrugCode(FinishAdviceRequest("2",viewModel.prescriptioninfo.value,viewModel.Prescriptionbarcode))
                    }
                }
            }
            recyclerView.adapter = adapter
        }
    }

    override fun initData() {
       val dateStr = intent.getStringExtra("date")
        if (!dateStr.isNullOrEmpty()){
            val date = CommonUtils.parseDate(dateStr)
            calendarStart.time = date
        }
       val rxno = intent.getStringExtra("rxno")
        /*  if (!rxno.isNullOrEmpty()){
              viewModel.rxno = rxno
          }*/
        startDate = "${calendarStart.get(Calendar.YEAR)}-${calendarStart.get(Calendar.MONTH) + 1}-${calendarStart.get(Calendar.DAY_OF_MONTH)}"
        binding.tvDate.text = startDate
         patientId = intent.getStringExtra("patientId")
        viewModel.getDoctorOrderedInfoList(Gson().toJson(AdviceRequest(startDate,patientId,rxno)))
    }

    override fun startObserve() {
        viewModel.baseUiModel.observe(this, Observer {
            if (it.showLoading){
                showMyDialog(resources.getString(R.string.getting_data))
            }else{
                dismissMyDialog()
            }
            if (!it.showError.isNullOrEmpty()){
                BlueDialog(this,it.showError!!,type = 1){}
            }
            if (it.showSuccess==true){
                showCompleteToast(this)
                finish()
//                viewModel.getDoctorOrderedInfoList(Gson().toJson(AdviceRequest(startDate,patientId)))
            }
        })
        viewModel.uiState.observe(this, Observer {
            if (it.isLoading){
                showMyDialog(resources.getString(R.string.getting_data))
            }else{
                dismissMyDialog()
            }
        })
        viewModel.prescriptioninfo.observe(this, Observer { list->
            try {
                if (!list.isNullOrEmpty()&& list.isNotEmpty()){
                    val prescr = list[0]
                    adapter.removeAllHeaderView()
                    prescr.let {
                        adapter.setCanScan(viewModel.canAdd)
                        if (viewModel.canAdd){
                            binding.llBottom.visibility = View.VISIBLE
                        }else{
                            binding.llBottom.visibility = View.GONE
                        }
                            val view =  LayoutInflater.from(this).inflate(R.layout.layout_drup_collect_top_view,null)
                            val bind = DataBindingUtil.bind<LayoutDrupCollectTopViewBinding>(view)
                            bind?.apply {
                                tvDate.text = "用药日期：${it.prescriptionTime?.substring(0,10)}"
                                tvName.text = it.psnName
                            }
                            adapter.addHeaderView(view)
                    }
                    adapter.setList(viewModel.showList)
                    /*if(!viewModel.rxno.isNullOrEmpty()){
                        viewModel.showList.forEachIndexed { index, drugInfoBean ->
                            if (drugInfoBean.rxno==viewModel.rxno){
                                viewModel.selectIndex.postValue(index)
                            }
                        }
                        viewModel.rxno = ""
                    }*/
                }else{
                    binding.llBottom.visibility = View.GONE
                    adapter.removeAllHeaderView()
                    adapter.setList(mutableListOf())
                    adapter.setEmptyView(R.layout.layout_nodata)
                    viewModel.selectIndex.value = -1
                }
            } catch (e: Exception) {
            }

        })
        viewModel.selectIndex.observe(this, Observer {
            try {
                var trugTracCodgIsGatherCount = 0
               adapter.data.forEach { drugInfoBean ->
                   viewModel.trugTracCodgIsGatherData?.drugDictInfo?.forEach { temp ->
                       if (drugInfoBean.drugCode == temp.drugCode) {
                           if (drugInfoBean.drugTracInfoList != null && drugInfoBean.drugTracInfoList!!.size > 0) {
                               drugInfoBean.drugTracInfoList?.forEach { drug ->
                                   if (drug.drugTracCodg == viewModel.barcode) {
                                       if (drug.drugTracCodeNum != null) {
                                           trugTracCodgIsGatherCount += drug.drugTracCodeNum!!.toInt()
                                       } else {
                                           trugTracCodgIsGatherCount++
                                       }
                                   }
                               }

                           }
                       }
                   }
               }
                adapter.data.forEachIndexed { index, drugInfoBean ->
                    drugInfoBean.isSelected = it == index
                    if (viewModel.barcode.isNotEmpty()) {
                        if (it == index ) {
                            var setAllCount = 0
//                            var setBarcodeCount = 0
                            drugInfoBean.drugTracInfoList?.forEach { drug ->
                                if (drug.drugTracCodeNum != null) {
                                    setAllCount += drug.drugTracCodeNum!!.toInt()
//                                    if (drug.drugTracCodg == viewModel.barcode) {
//                                        setBarcodeCount += drug.drugTracCodeNum!!.toInt()
//                                    }
                                } else {
                                    setAllCount++
//                                    if (drug.drugTracCodg == viewModel.barcode) {
//                                        setBarcodeCount++
//                                    }
                                }
                            }

                            // 解析药品总量
                            val maxNum = try {
                                drugInfoBean.drugNum!!.toDouble().toInt()
                            } catch (e: Exception) {
                                e.printStackTrace()
                                1
                            }
                            // 处理拆零系数 如果coff为空时的处理
                            var ipcoff = 0
                            ipcoff = try {
                                drugInfoBean.ipCoff?.toInt() ?: 0
                            } catch (e: Exception) {
                                e.printStackTrace()
                                0
                            }
                            if (ipcoff > 0) {
                                if (ipcoff - viewModel.usedCount.toInt() - trugTracCodgIsGatherCount <= 0) {
                                    BlueDialog(this, "该溯源码已绑定完毕，请更换溯源码", type = 1) {}
                                    return@Observer
                                }
                            }
                            if (maxNum == setAllCount) {
                                drugInfoBean.trugTracCodgIsGatherCount=true
                                viewModel.trugTracCodgIsGather(viewModel.barcode)
                                Toast.makeText(this,"该药品溯源码添加超过上限", Toast.LENGTH_SHORT).show()
//                                BlueDialog(this, "该药品溯源码添加超过上限", type = 1) { }
                                return@Observer
                            }

                        }

                    }
                }
                if (it!=-1){
                    binding.recyclerView.layoutManager?.scrollToPosition(it+1)
                    adapter.data[it].isSelected = true
                    if (viewModel.barcode.isNotEmpty()){
                        if(adapter.data[it].drugTracInfoList==null){
                            adapter.data[it].drugTracInfoList = mutableListOf()
                        }
                        var drugTracCodeNum = countDrugTracCodeNums(adapter.data[it])
                        val drugTrace = DrugTrace(drugTracCodg = viewModel.barcode,drugTracCodeNum = drugTracCodeNum)
                        adapter.data[it].drugTracInfoList!!.add(drugTrace)
                       /* if (adapter.data[it].drugTracInfoList?.size == adapter.data[it].drugNum?.toDouble()
                                        ?.toInt()
                        ){
                            viewModel.selectIndex.value=-1
                        }*/
//                        var alert = false
//                        var size = 0
//                        adapter.data[it].drugTracInfoList?.forEach { drugInfo ->
//                            if (drugInfo.drugTracCodeNum != null) {
//                                size += drugInfo.drugTracCodeNum!!.toInt()
//                            } else {
//                                size++
//                            }
//                        }
//                        var needCount = 0
//                        needCount = try {
//                            adapter.data[it].drugNum?.toDoubleOrNull()?.toInt() ?: 0
//                        } catch (e: Exception) {
//                            0
//                        }
//                        if (size < needCount) {
//                            alert = true
//                        }
//                        if (!alert){
//                            viewModel.selectIndex.value=-1
//                        }
                    }
                }
                adapter.notifyDataSetChanged()
            } catch (e: Exception) {
            }
//            if (viewModel.lastIndex!=-1)
//            adapter.notifyItemChanged(viewModel.lastIndex)
        })

    }
    fun countDrugTracCodeNum(drugInfoBean: DrugInfoBean): Integer {
        if (drugInfoBean.trdnFlag != "1") return Integer(1)
        var maxNum = 1
        var scanNum = 0
        try {
            maxNum = drugInfoBean.drugNum!!.toDouble().toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        drugInfoBean.drugTracInfoList?.forEach {
            try {
                scanNum += it.drugTracCodeNum!!.toInt()
            } catch (e: Exception) {
            }
        }
        var count = maxNum - scanNum
        if (count < 1) count = 1
        return Integer(count)
    }
    private fun countDrugTracCodeNums(drugInfoBean: DrugInfoBean): Integer {
        // 初始化一个变量来保存计算结果
        var count = 1
        if (drugInfoBean.trdnFlag != "1") {
            // 如果不是追踪药品，固定返回1
            return Integer(count)
        }
        // 解析药品总量
        val maxNum = try {
            drugInfoBean.drugNum!!.toDouble().toInt()
        } catch (e: Exception) {
            e.printStackTrace()
            1
        }

        // 处理拆零系数 如果ipcoff为空时的处理
        var ipcoff: Int? = try {
            drugInfoBean.ipCoff?.toInt()?.coerceAtLeast(1)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }

        var usedCount = 0
        if (!viewModel.usedCount.isNullOrEmpty()) {
            usedCount = viewModel.usedCount!!.toInt()
        }
        if (ipcoff != null) {
            ipcoff -= usedCount
        }


        // 计算已扫描总量
        var scanNum = 0
        drugInfoBean.drugTracInfoList?.forEach {
            try {
                scanNum += it.drugTracCodeNum!!.toInt()
            } catch (e: Exception) {
                // 忽略无效值
            }
        }

        // 计算剩余未扫描数量
        val remaining = maxNum - scanNum
        if (ipcoff == null) {
            //如果拆零系数为空
            count = if (scanNum == 0) {
                // 第一次扫码：返回全部数量
                maxNum
            } else {
                // 后续所有扫码：固定返回1
                1
            }
        } else if (maxNum <= ipcoff) {
            // 规则1: 如果药品总量小于等于拆零系数
            count = if (scanNum == 0) {
                // 第一次扫码：返回全部数量
                maxNum
            } else {
                // 后续扫码：固定返回1
                1
            }
        }
        // 规则2: 药品总量大于拆零系数
        else {
            count = when {
                // 如果剩余数量大于等于拆零系数，返回拆零系数
                remaining >= ipcoff -> ipcoff

                // 如果还有剩余（但不足一个整包装），返回剩余数量
                remaining > 0 -> remaining

                // 如果剩余为0或负数，返回1
                else -> 1
            }
        }

        // 在方法最后统一将count转换为Integer返回
        return Integer(count)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(message: EventMessage?) {
        message?.apply {
            //扫码拿到barcode了，去请求接口
            when (message.messageCode) {
                MessageCode.SCAN_BARCODE -> {
                    if (KtxManager.isTopActivity(this@DoctorAdviceCollectionActivity)){
                        val barcodeMessage = this.any as BarcodeMessage
                        if(barcodeMessage.type== BarcodeType.SUYUAN){
                            if (viewModel.canAdd){
                                //扫码去
                                viewModel.trugTracCodgIsGather(barcodeMessage.barcode)
                            }
                        }else{
                            YellowDialog(this@DoctorAdviceCollectionActivity,resources.getString(R.string.scan_suyuan),type = 1){}
                        }

                    }
                }
            }
        }
    }
    private val calendarStart = Calendar.getInstance()
    private var startDatePicker : DatePickerDialog? = null
    private var startDate:String=""
    private fun showDatePicker(){
        if (startDatePicker==null){
            startDatePicker = DatePickerDialog(
                this,
                { _, year, monthOfYear, dayOfMonth ->
                    calendarStart.set(year, monthOfYear, dayOfMonth)
                    startDate = "${calendarStart.get(Calendar.YEAR)}-${calendarStart.get(Calendar.MONTH) + 1}-${calendarStart.get(Calendar.DAY_OF_MONTH)}"
                    binding.tvDate.text = startDate
                    viewModel.getDoctorOrderedInfoList(Gson().toJson(AdviceRequest(startDate,patientId)))
                },
                calendarStart.get(Calendar.YEAR), calendarStart.get(Calendar.MONTH), calendarStart.get(
                    Calendar.DAY_OF_MONTH)
            )
        }
        startDatePicker?.show()
    }
    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}